package com.shadt.cloud.filter;

import java.io.IOException;
import java.text.ParseException;
import java.util.Date;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;

import com.shadt.cloud.service.BranchService;
import com.shadt.cloud.util.ContainsUtil;
import com.shadt.cloud.vo.BranchVo;
import com.shadt.core.util.DateUtil;
import com.shadt.core.util.MD5Util;
import com.shadt.core.util.SpringUtil;

/**
 * 平台权限拦截器
 * 
 * @author SongR
 *
 */
public class BranchAuthorityFilter implements Filter {
	Logger log = Logger.getLogger(this.getClass());
	
	@Autowired
	BranchService service;

	public BranchAuthorityFilter() {
	}

	public void destroy() {
		
	}

	

	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		HttpServletRequest r = (HttpServletRequest) request;
		String url = r.getRequestURI();//获取url
		String [] urls = {"api"};//拦截的路径
		/*
		 * 当访问的url包含
		 */
		if(ContainsUtil.check(url, urls)&&request.getParameter("skip")==null){
			log.info("调用接口的路径为:"+url);
			String appName = request.getParameter("appname");
			String param =request.getParameter("param");
			String time = request.getParameter("time");
			String sign = request.getParameter("sign");
			log.info("appName="+appName+"\tparam="+param+"\ttime="+time+"\tsign="+sign);
			if(appName.equals("")||time.equals("")||param.equals("")||sign.equals("")){
				log.info("参数不能为空！");
				((HttpServletResponse) response).setHeader("content-type", "text/html;charset=UTF-8");
				((HttpServletResponse) response).getWriter().println("{'msg':'参数不正确！','success':false}");
			}else{
				if(time.length()>10){
					log.info("请传入10位时间戳");
				}else{
					try {
						String timenow = DateUtil.dateToStamp(DateUtil.dataToStr(new Date(), "yyyy-MM-dd HH:mm:ss"));
						Long t = new Long(timenow)-new Long(time+"000");
						log.info("当前时间戳:"+timenow+"\t传递的时间戳"+time+"000\t"+t/1000);
						if(t/1000>-600&&t/1000<=600){
							BranchVo vo = null;
							try{
								vo = service.getBranch(appName);
							}catch (Exception e) {
								log.error("获取app异常！",e);
								((HttpServletResponse) response).setHeader("content-type", "text/html;charset=UTF-8");
								((HttpServletResponse) response).getWriter().println("{'msg':'系统异常！','success':false}");
							}
							if(null!=vo&&vo.getStatus()==0){
								String s = MD5Util.md5("appname="+appName+"param="+param+"time="+time+vo.getSecret());
								if(s.equals(sign)){
									log.info("参数验证成功！");
									chain.doFilter(request, response);
								}else{
									log.info("参数验证失败！");
									((HttpServletResponse) response).setHeader("content-type", "text/html;charset=UTF-8");
									((HttpServletResponse) response).getWriter().println("{'msg':'参数验证失败！','success':false}");
								}
							}else{
								((HttpServletResponse) response).setHeader("content-type", "text/html;charset=UTF-8");
								((HttpServletResponse) response).getWriter().println("{'msg':'平台不存在或为不可用状态！','success':false}");
							}
						}else{
							log.info("时间戳已过期！");
							((HttpServletResponse) response).setHeader("content-type", "text/html;charset=UTF-8");
							((HttpServletResponse) response).getWriter().println("{'msg':'时间过期！','success':false}");
						}
						
					} catch (ParseException e1) {
						log.error("时间转换异常！",e1);
						((HttpServletResponse) response).setHeader("content-type", "text/html;charset=UTF-8");
						((HttpServletResponse) response).getWriter().println("{'msg':'系统异常！','success':false}");
					}
				}
			}
		}else{
			log.info("跳过参数验证！");
			chain.doFilter(request, response);
		}
	}
	
	public static void main(String[] args) throws ParseException {
		String timenow = DateUtil.dateToStamp(DateUtil.dataToStr(new Date(), "yyyy-MM-dd HH:mm:ss"));
		timenow = timenow.substring(0, timenow.length()-3);
//		System.out.println(MD5Util.md5("a=1b=2c=3a1b2c3"));
		String s = MD5Util.md5("appname=SongRparam="
				+ "[{'key':'ZJLYZQDL','start':68447,'size':10},{'key':'CLOUD1000HOMENEWS','start':30903,'size':2},"
				+ "{'key':'CLOUD1000INTERNATIONALNEWS','start':30918,'size':2},{'key':'CLOUD1000SPORTS','start':30933,'size':12},{'key':'CLOUD1000ENTERTAINMENT','start':31027,'size':2},{'key':'CLOUD1000ECNOMICS','start':30981,'size':12},{'key':'CLOUD1000SCIENCEANDTECHNOLOGY','start':30991,'size':2},{'key':'CLOUD1000MILITARY','start':30999,'size':2},{'key':'CLOUD1000SOCIOLOGY','start':31004,'size':2}]"
				+ "time="+timenow+"lPnkj7bvCRfbxJyccqjnn3gLAWOs5Ejc");
		System.out.println(timenow);
		System.out.println(s);
	}

	public void init(FilterConfig fConfig) throws ServletException {
		service = (BranchService) SpringUtil.getBean("branchServiceImpl");
	}
	
}
